import { Button, Input, Modal, Radio, Space, TableProps, message } from "antd";
import React, { useEffect, useState } from "react";
import style from "./index.module.scss";
import Search, { SearchProps } from "antd/lib/input/Search";
import TableCom from "../TableCom";
import { addType, delType, editType, getType } from "@/api";
import { KindsManageType, selectedKindsRowsType } from "@/configs/types";
export function TypesManage() {
  const typeColumns = [
    {
      title: "类型名称",
      dataIndex: "typeName",
      key: "typeName",
      align: "center",
    },
    {
      title: "操作",
      dataIndex: "todo",
      key: "todo",
      align: "center",
      render: (text: string, record: any) => (
        <Space>
          <Button onClick={() => handleDel(record.id)}> 删除</Button>
          <Button onClick={() => handleEdit(record.id)}> 编辑</Button>
        </Space>
      ),
    },
  ];
  const [selectedType, setSelectedType] = useState("post");
  const [typeArr, setTypeArr] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [inputValue, setInputValue] = useState("");
  const [pageOptions, setPageOptions] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [selectedRowsData, setSelectedRowsData] =
    useState<selectedKindsRowsType>({
      selectedRowKeys: [],
      selectedRows: [],
    });
  const [typeId, setTypeId] = useState(0);
  const handleDel = async (id: number | number[]) => {
    const categoryIds = typeof id === "number" ? [id] : id;
    const res = await delType(categoryIds);
    if (res.data.code === 200) {
      message.success(res.data.msg);
      getTypeArr(pageOptions.current, pageOptions.pageSize, selectedType);
    } else {
      message.error(res.data.msg);
    }
  };
  const handleEdit = async (id: number) => {
    setIsModalOpen(true);
    setTypeId(id);
  };

  const handleOk = async () => {
    const res = await addType({
      differ: selectedType,
      id: typeId,
      typeName: inputValue,
    });
    if (res.data.code === 200) {
      message.success(res.data.msg);
      getTypeArr(pageOptions.current, pageOptions.pageSize);
      setInputValue("");
      setTypeId(0);
      setIsModalOpen(false);
    } else {
      message.error(res.data.msg);
    }
  };

  const handleCancel = () => {
    setTypeId(0);
    setInputValue("");
    setIsModalOpen(false);
  };
  //  根据类型名查询
  const onTypeSearch: SearchProps["onSearch"] = async (value, _e, info) => {
    getTypeArr(1, paginationOptions.pageSize, value);
  };
  const getTypeArr = async (
    pageNum: number = 1,
    pageSize: number = 10,
    typeName?: string
  ) => {
    const res = await getType({
      differ: selectedType,
      pageNum,
      pageSize,
      typeName,
    });
    setPageOptions({
      pageSize,
      total: res.data.data.total,
      current: pageNum,
    });
    setTypeArr(res.data.data.records);
  };
  //分页
  const handlePageChange = (current: number, pageSize: number) => {
    getTypeArr(current,pageSize);
  };
  const paginationOptions = {
    current: pageOptions.current,
    pageSize: pageOptions.pageSize,
    showQuickJumper: true,
    total: pageOptions.total,
    showTotal: (total: number) => `共 ${total} 条`,
    onChange: handlePageChange,
  };

  const rowSelection: TableProps<KindsManageType>["rowSelection"] = {
    onChange: (
      selectedRowKeys: React.Key[],
      selectedRows: KindsManageType[]
    ) => {
      setSelectedRowsData({ selectedRowKeys, selectedRows });
    },
    getCheckboxProps: (record) => ({
      disabled: record.typeName === "Disabled User", // Column configuration not to be checked
      name: record.typeName,
    }),
    selectedRowKeys: selectedRowsData.selectedRowKeys,
  };
  useEffect(() => {
    getTypeArr();
  }, [selectedType]);
  return (
    <div className={style["Container"]}>
      <div className={style["header"]}>
        <Space>
          <Search
            placeholder="搜索类型名称"
            onSearch={onTypeSearch}
            style={{ width: 200 }}
            maxLength={32}
          />
          <Button
            onClick={() =>
              handleDel(selectedRowsData.selectedRowKeys as number[])
            }
          >
            批量删除
          </Button>
          <Radio.Group
            onChange={(e) => setSelectedType(e.target.value)}
            value={selectedType}
          >
            <Radio value={"post"}>帖子</Radio>
            <Radio value={"video"}>课程</Radio>
          </Radio.Group>
          <Button onClick={() => setIsModalOpen(true)}>添加类型</Button>
        </Space>
      </div>
      <div className={style["content"]}>
        <TableCom
          dataSource={typeArr}
          columns={typeColumns}
          paginationOptions={paginationOptions}
          rowSelection={rowSelection}
        />
        <Modal
          title={typeId ? "编辑类型" : "添加类型"}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Input
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
          ></Input>
        </Modal>
      </div>
    </div>
  );
}
